import { animation, AnimationClip, JsonAsset, Label, Layers, math, Node, Rect, Sprite, SpriteFrame, sys, UITransform, Vec2 } from "cc"
import DataManager from "../Runtime/DataManager"
import ResourceManager from "../Runtime/ResourceManager"
import { ChargingEnemy } from "../Npc/ChargingEnemy"
import { DumbEnemy } from "../Npc/DumbEnemy"
import { HelmetEnemy } from "../Npc/HelmetEnemy"
import { LeapingEnemy } from "../Npc/LeapingEnemy"
import { userStore } from "../service/user"
import { GAME_MODE_ENUM } from "../../Enums"
import { StoneManager } from "../Property/StoneManager"
import { BombManager } from "../Property/BombManager"
import { BrickManager } from "../Property/BrickManager"
import { HeavyManager } from "../Property/HeavyManager"
import { JellyManager } from "../Property/JellyManager"
// 创建节点
export const createUINode = (name: string = '') => {
    const node = new Node(name)
    node.addComponent(UITransform)
    node.layer = 1 << Layers.nameToLayer("UI_2D")
    return node
}
// 创建节点
export const createUILabel = async ({ parentNode, fontSize = 34, color = DataManager.Instance.color, text = "", lineHeight = 40 }) => {
    let font = DataManager.Instance.font
    const label = parentNode.addComponent(Label)
    label.string = text
    label.color = new math.Color(color)
    label.useSystemFont = false
    label.font = font[0]
    label.fontSize = fontSize
    label.enableOutline = true
    label.outlineWidth = 5
    label.lineHeight = lineHeight
    return label
}
// 数组分组
export const chunkArray = (array, size) => {
    let result = [];
    for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
    }
    return result;
};

// 字符串变数组
export const stringWidthArray = (string: string) => {
    return string.split(',')
}
// 生成随机数
export function getRandomNumber(min, max) {
    let random=Math.floor(DataManager.Instance.seed_random() * (max - min + 1)) + min
    // console.log(random)
    return random
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
// const ANIMATION_SPEED = 1 / 10
// 根据图片数组设置帧动画
export function setListTrantion(spriteList: SpriteFrame[], name: string, warpMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Loop, animation_speed = 1 / 20) {
    let animationClip: AnimationClip = new AnimationClip();
    const track = new animation.ObjectTrack();
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame');
    const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteList).map((item: SpriteFrame, index: number) => [index * animation_speed, item])
    track.channel.curve.assignSorted(frames);
    animationClip.duration = spriteList.length * animation_speed
    animationClip.name = name;
    animationClip.addTrack(track);
    animationClip.wrapMode = warpMode
    return animationClip
}
// 根据图片数组设置尺寸轨道动画
export function setSizeTrackTrantion(vec3KeyFrames, name: string, toProperty: string = 'scale', warpMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Loop,) {
    let animationClip: AnimationClip = new AnimationClip();

    const track = new animation.VectorTrack(); // 创建一个向量轨道
    track.path = new animation.TrackPath().toProperty(toProperty);
    const [x, y] = track.channels(); // x, y, z 是前三条通道
    x.curve.assignSorted(vec3KeyFrames.map(([time, vec3]) => [time, { value: vec3.x }]));
    y.curve.assignSorted(vec3KeyFrames.map(([time, vec3]) => [time, { value: vec3.y }]));
    animationClip.duration = vec3KeyFrames[vec3KeyFrames.length - 1][0]
    animationClip.name = name;
    animationClip.addTrack(track);
    animationClip.wrapMode = warpMode
    animationClip.addTrack(track);
    return animationClip
}
// 裁剪SpriteFrame
export function getRectSprite(spriteFrame: SpriteFrame, x: number, y: number, width: number, height: number) {
    const sectionSprite = spriteFrame.clone();
    const rect = new Rect(x, y, width, height);
    sectionSprite.rect = rect;
    return sectionSprite
}

export function getUniqueArray(list) {
    let seen = new Map();
    let uniqueArray = list.filter(obj => {
        if (!seen.has(obj.type)) {
            seen.set(obj.type, true);
            return true;
        }
        return false;
    });
    return uniqueArray
}
// 给spriteFrame排序
export const sortSpriteFrame = (spriteList: SpriteFrame[]) => spriteList.sort((a, b) => { return parseInt(a.name.replace(/\D/g, "")) - parseInt(b.name.replace(/\D/g, "")) })
// 生成椭圆形的坐标点
export function generateEllipsePoints(width = DataManager.Instance.width / 2 - 4, height = DataManager.Instance.position / 2 - 4, length = 35) {
    let points = [];
    for (let i = 0; i < length; i++) {
        let angle = (2 * Math.PI / length) * i;
        let x = (Math.cos(angle) * width).toFixed(2);
        let y = (Math.sin(angle) * height).toFixed(2);
        points.push(new Vec2(Number(x), Number(y)));
    }
    return points;
}
// 防抖
export function debounce(fn, wait) {
    let timeout = null;
    return () => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
            fn.apply(this, arguments);
        }, wait);
    };
}
// 把数字变为最接近的整数
export function roundToNearestInteger(num) {
    return Math.sign(num) * Math.round(Math.abs(num));
}
// 加载图片数组和动画
export function loadAnimationClip(assets, name, wrapMode: AnimationClip.WrapMode) {
    let list = assets.jsonAsset.filter(item => item.filename.includes(`${name}`))
    let frame = getFrameAllAsset(assets, list)
    return { frame, animation: setListTrantion(frame, name, wrapMode) }
}

// 在原层级创建占位node
export function createPlaceholder(node: Node) {
    let name = "placeholder"
    if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
        name = "placeholder" + node.name
    }
    const placeholder_node = createUINode(name)
    placeholder_node.setParent(node.parent)
    placeholder_node.setSiblingIndex(node.getSiblingIndex())
    if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
        DataManager.Instance.async_scence.push({
            type: 'property', node: placeholder_node.name, player: {
                index: node.getSiblingIndex(),
                parent: node.parent.name,
                name
            }
        })
    }
}
// 获取道具的manager
export function getPropertyManager(node) {
    if (node.name.includes('stone')) {
        return StoneManager
    } else if (node.name.includes('bomb')) {
        return BombManager
    } else if (node.name.includes('jelly')) {
        return JellyManager
    } else if (node.name.includes('heavy')) {
        return HeavyManager
    } else if (node.name.includes('brick')) {
        return BrickManager
    }
}
// 获取大图下的多个小图
export function getFrameAllAsset(JosnAndSpriteFrame, list: Array<any>) {
    let { spriteFrame, jsonAsset } = JosnAndSpriteFrame
    let array = []
    list.forEach(item1 => {
        let temple = jsonAsset.find(item => item.filename == item1.filename)
        let sf = getRectSprite(spriteFrame[0], temple.frame.x, temple.frame.y, temple.sourceSize.w, temple.sourceSize.h)
        array.push(sf)
    })
    return array
}

// 获取json和大图
export async function loadJosnAndSpriteFrame(path, name) {
    let spriteFrame = await ResourceManager.Instance.loadDir(path, SpriteFrame)
    let jsonAsset = await ResourceManager.Instance.loadDir(path, JsonAsset)
    let jsonFrames = jsonAsset.find(item => item.name == name)?.json?.frames
    return { spriteFrame, jsonAsset: jsonFrames }
}
// 获取json下的某一张图
export function getFrameAsset(JosnAndSpriteFrame, filename: string) {
    let { spriteFrame, jsonAsset } = JosnAndSpriteFrame
    let temple = jsonAsset.find(item => item.filename == filename)
    let sf = getRectSprite(spriteFrame[0], temple.frame.x, temple.frame.y, temple.sourceSize.w, temple.sourceSize.h)
    return { temple, spriteFrame: sf }
}

// 获取怪物的manager
export function getEnemyManager(node) {
    let children = node.children[0]
    if (children.name.includes('Leaping')) {
        return LeapingEnemy
    } else if (children.name.includes('Helmet')) {
        return HelmetEnemy
    } else if (children.name.includes('Dumb')) {
        return DumbEnemy
    } else if (children.name.includes('Charging')) {
        return ChargingEnemy
    }
}
// 深度合并
export function deepMerge(a: any, b: any) {
    let k;
    for (k in b) {
        a[k] =
            a[k] && a[k].toString() === "[object Object]" ? deepMerge(a[k], b[k]) : (a[k] = b[k]);
    }
    return a;
}

// 5毫秒后销毁元素
export function destroyNode(node) {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => {
            if (node && node.isValid) {
                node.destroy();
                resolve();
                return;
            }
            reject();
        }, 5);
    });
}

// 设置图片数组
export function setRoleloadDir(name = "dumb_enemy", enmu) {
    let jsonList = DataManager.Instance.enemyAssets.jsonAsset.filter(item => item.filename.includes(`${name}`))
    let typeList = []
    for (let key in enmu) {
        if (enmu.hasOwnProperty(key)) { // 确保key是对象自身的属性
            typeList.push(enmu[key])
        }
    }
    let list = []
    for (let i = 0; i < typeList.length; i++) {
        let item = typeList[i]
        let animation_speed = 1 / 20
        if (item.includes("fly") && !item.includes("fly_ing")) {
            animation_speed = 1 / 10
        }
        let secondPath = item.replace("left", "right")
        let title = `${name}/${secondPath}/`
        let spriteList = jsonList.filter(item => item.filename.includes(`${title}`))
        list.push({
            type: item,
            name: name + '_' + item,
            spriteList: getFrameAllAsset(DataManager.Instance.enemyAssets, spriteList),
            wrapMode: item.includes('avoid') ? AnimationClip.WrapMode.Normal : AnimationClip.WrapMode.Loop,
            animation_speed
        })
    }
    return list
}

export function showToast(title) {
    const wx = window['wx']
    if (typeof (wx) !== "undefined") {
        wx.showToast({
            title,
            icon: "none"
        })
    }
}
export function getSetting() {
    const wx = window['wx']
    if (typeof (wx) !== "undefined") {
        return "wx"
    } else {
        return "other"
    }
}
// 获取接收消息方的id,当前角色是房主，就给成员发
export function getSendId() {
    let room = DataManager.Instance.room
    let id = userStore().info?.id
    if (!room?.id || !id) return ""
    if (id == room.ownerId) {
        return room.memberId
    } else {
        return room.ownerId
    }
}

export function generateUUID() {
    let timestamp = new Date().getTime();
    const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (timestamp + Math.random() * 16) % 16 | 0;
        timestamp = Math.floor(timestamp / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}
